// +----------------------------------------------------------------------
// | WYS [ WYS赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014~2024 https://www.wshbin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed WYS并不是自由软件，未经许可不能去掉WYS相关版权
// +----------------------------------------------------------------------
// | Author: WYS Team <admin@wys.com>
// +----------------------------------------------------------------------

// #ifdef H5
import { getWechatConfig, getShopConfig, wechatAuthV2 } from '@/api/public'
import { WX_AUTH, STATE_KEY, LOGINTYPE, BACK_URL } from '@/config/cache'
import { parseQuery } from '@/utils'
import { HTTP_REQUEST_URL } from '@/config/app'
import store from '@/store'
import Cache from '@/utils/cache'

class AuthWechat {
  constructor() {
    console.log('jWeixin', jWeixin)
    this.instance = jWeixin
    //是否实例化
    this.status = false

    this.initConfig = {}
  }

  isAndroid() {
    let u = navigator.userAgent
    return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
  }

  signLink() {
    if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
      window.entryUrl = location.href
    }
    return HTTP_REQUEST_URL // /(Android)/i.test(navigator.userAgent) ? location.href : window.entryUrl;
  }

  setCustomShareContent() {
    // 设置分享给好友的内容
    this.instance.updateAppMessageShareData({
      title: '自定义的分享标题', // 分享标题
      desc: '自定义的分享描述', // 分享描述
      link: 'https://你的分享链接.com', // 分享链接
      imgUrl: 'https://你的分享图片链接.com/image.jpg', // 分享图标
      success: function () {
        console.log('分享给好友设置成功')
      }
    })

    // 设置分享到朋友圈的内容
    this.instance.updateTimelineShareData({
      title: '自定义的朋友圈分享标题', // 分享标题
      link: 'https://你的分享链接.com', // 分享链接
      imgUrl: 'https://你的分享图片链接.com/image.jpg', // 分享图标
      success: function () {
        console.log('分享到朋友圈设置成功')
      }
    })
  }
  /**
   * 初始化wechat(分享配置)
   */
  wechat() {
    return new Promise((resolve, reject) => {
      console.log('Jweixin', jWeixin)
      getWechatConfig()
        .then((res) => {
          console.log('微信初始化>>>>>', res)
          console.log('当前 wx 实例:', this.instance)
          console.log('配置数据:', res.data)
          this.instance.config(res.data)
          this.instance.error(function (res) {
            console.error('wx.config 配置错误:', res)
          })
          console.log('wx 实例状态:', this.instance)
          this.initConfig = res.data
          this.status = true
          console.log('配置成功，准备调用 ready 方法')
          console.log('新 wx ', this.instance)
          if (!this.instance) {
            console.log('wx 实例未初始化')
            return
          }
          this.instance.ready(() => {
            console.log('ready 方法被调用')
            this.setCustomShareContent()
            resolve(this.instance)
          })
        })
        // .then((res) => {
        //   console.log('微信初始化>>>>>', res)
        //   console.log('+++', this.instance)
        //   this.instance.config(res.data)
        //   this.initConfig = res.data
        //   this.status = true
        //   this.instance.ready(() => {
        //     resolve(this.instance)
        //   })
        // })
        .catch((err) => {
          console.log('微信初始化失败>>>>>', err)
          this.status = false
          reject(err)
        })
    })
  }

  /**
   * 验证是否初始化
   */
  verifyInstance() {
    let that = this
    return new Promise((resolve, reject) => {
      if (that.instance === null && !that.status) {
        that
          .wechat()
          .then((res) => {
            resolve(that.instance)
          })
          .catch(() => {
            return reject()
          })
      } else {
        return resolve(that.instance)
      }
    })
  }
  // 微信公众号的共享地址
  openAddress() {
    return new Promise((resolve, reject) => {
      this.wechat()
        .then((wx) => {
          this.toPromise(wx.openAddress)
            .then((res) => {
              resolve(res)
            })
            .catch((err) => {
              reject(err)
            })
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  // 获取经纬度；
  location() {
    return new Promise((resolve, reject) => {
      this.wechat()
        .then((wx) => {
          this.toPromise(wx.getLocation, { type: 'wgs84' })
            .then((res) => {
              resolve(res)
            })
            .catch((err) => {
              reject(err)
            })
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  // 使用微信内置地图查看位置接口；
  seeLocation(config) {
    return new Promise((resolve, reject) => {
      this.wechat()
        .then((wx) => {
          this.toPromise(wx.openLocation, config)
            .then((res) => {
              resolve(res)
            })
            .catch((err) => {
              reject(err)
            })
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  /**
   * 微信支付
   * @param {Object} config
   */
  pay(config) {
    return new Promise((resolve, reject) => {
      this.wechat()
        .then((wx) => {
          this.toPromise(wx.chooseWXPay, config)
            .then((res) => {
              resolve(res)
            })
            .catch((res) => {
              reject(res)
            })
        })
        .catch((res) => {
          reject(res)
        })
    })
  }

  toPromise(fn, config = {}) {
    return new Promise((resolve, reject) => {
      fn({
        ...config,
        success(res) {
          resolve(res)
        },
        fail(err) {
          reject(err)
        },
        complete(err) {
          reject(err)
        },
        cancel(err) {
          reject(err)
        }
      })
    })
  }

  /**
   * 自动去授权
   */
  oAuth(snsapiBase, url) {
    if (uni.getStorageSync('authIng')) return
    if (uni.getStorageSync(WX_AUTH) && store.state.app.token && snsapiBase == 'snsapi_base') return

    let { code } = parseQuery()
    let snsapiCode = uni.getStorageSync('snsapiCode')

    if (code instanceof Array) {
      code = code[code.length - 1]
    }
    if (snsapiCode instanceof Array) {
      snsapiCode = snsapiCode[snsapiCode.length - 1]
    }
    if (!code || code == snsapiCode) {
      uni.setStorageSync('authIng', true)
      return this.toAuth(snsapiBase, url)
    } else {
      if (Cache.has('snsapiKey')) {
        return this.auth(code).catch((error) => {
          uni.showToast({
            title: error || '授权失败，请稍后重试',
            icon: 'none'
          })
        })
      }
    }
  }

  clearAuthStatus() {}

  /**
   * 授权登陆获取token
   * @param {Object} code
   */
  auth(code) {
    return new Promise((resolve, reject) => {
      let loginType = Cache.get(LOGINTYPE)
      wechatAuthV2(code, parseInt(Cache.get('spid')))
        .then(({ data }) => {
          Cache.set(WX_AUTH, code)
          Cache.clear(STATE_KEY)
          resolve(data)
        })
        .catch(reject)
    })
  }

  /**
   * 获取跳转授权后的地址
   * @param {Object} appId
   */
  getAuthUrl(appId, snsapiBase, backUrl) {
    if (backUrl) {
      let backUrlArr = backUrl.split('&')
      let newUrlArr = backUrlArr.filter((item) => {
        if (item.indexOf('code=') === -1 || item.indexOf('back_url=') === -1 || item.indexOf('scope=') === -1) {
          return item
        }
      })
      backUrl = newUrlArr.join('&')
    }

    let url = `${location.origin}${backUrl}`

    if (url.indexOf('?') == -1) {
      url = url + '?'
    } else {
      url = url + '&'
    }
    const redirect_uri = encodeURIComponent(
      `${url}scope=${snsapiBase}&back_url=` +
        encodeURIComponent(encodeURIComponent(uni.getStorageSync(BACK_URL) ? uni.getStorageSync(BACK_URL) : location.pathname + location.search))
    )
    uni.removeStorageSync(BACK_URL)
    const state = encodeURIComponent(('' + Math.random()).split('.')[1] + 'authorizestate')
    uni.setStorageSync(STATE_KEY, state)
    if (snsapiBase === 'snsapi_base') {
      return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${state}&connect_redirect=1#wechat_redirect`
    } else {
      return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}&connect_redirect=1#wechat_redirect`
    }
  }

  /**
   * 跳转自动登陆
   */
  toAuth(snsapiBase, backUrl) {
    let that = this
    this.wechat().then((wx) => {
      location.href = this.getAuthUrl(that.initConfig.appId, snsapiBase, backUrl)
    })
  }

  /**
   * 绑定事件
   * @param {Object} name 事件名
   * @param {Object} config 参数
   */
  wechatEvevt(name, config) {
    let that = this
    return new Promise((resolve, reject) => {
      let configDefault = {
        fail(res) {
          if (that.instance)
            return reject({
              is_ready: true,
              wx: that.instance
            })
          that.verifyInstance().then((wx) => {
            return reject({
              is_ready: true,
              wx: wx
            })
          })
        },
        success(res) {
          return resolve(res, 2222)
        }
      }
      Object.assign(configDefault, config)
      that.wechat().then((wx) => {
        if (typeof name === 'object') {
          name.forEach((item) => {
            wx[item] && wx[item](configDefault)
          })
        } else {
          wx[name] && wx[name](configDefault)
        }
      })
    })
  }

  isWeixin() {
    return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
  }
}

export default new AuthWechat()
// #endif
